package com.wh.org.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.org.dao.IDepartmentDao;
import com.wh.org.dto.DepartmentDto;
import com.wh.org.pojo.Department;
import com.wh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private IDepartmentDao dao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
//    @CachePut(value = "department", key = "#")
    public void add(Department department) {
        dao.insert(department);
//        redisTemplate.delete("depTree");
    }

    @Override
    @Transactional
    public void del(Long id) {
        dao.deletefroId(id);
//        redisTemplate.delete("depTree");
    }

    @Override
    public void upd(Department department) {
        dao.updateById(department);
    }

    @Override
    public List<Department> findAll() {
        return dao.selectList(null);
    }

    @Override

    public Department findById(Long id) {
        return dao.selectById(id);
    }

    @Override
    public IPage<Department> findByPage(DepartmentDto departmentDto) {
        //1.创建查询条件
        QueryWrapper<Department> qw = new QueryWrapper<>();
        qw.like("name", departmentDto.getKeyword());
        qw.or();
        qw.like("sn", departmentDto.getKeyword());
        //2.创建分页参数
        IPage<Department> page = new Page<>(departmentDto.getCurrentPage(), departmentDto.getPageSize());
        //3.查询数据
        page.setRecords(dao.findByPage(page, qw));
        page.setTotal(dao.selectCount(qw));
//        List<Department> list = dao.findByPage(page, qw);
//        IPage<Department> page1 = page.setRecords(list);
        //4.返回结果
        return page;
    }

    @Override
    public void patchDel(Long[] ids) {
        dao.deleteBatchIds(Arrays.asList(ids));
//        redisTemplate.delete("depTree");
    }

    @Override
    //@Cacheable(value = "department", key = "'deptTree'", unless = "#result ==null and result.size()==0")
    public List<Department> deptTree() {

        List<Department> all = dao.selectList(null);

        Map<Long, Department> hashMap = new HashMap<>();
        for (Department department : all) {
            hashMap.put(department.getId(), department);
        }
//        创建部门树结果集，所有顶级存储 子部门存储于顶级
        List<Department> deptTree = new ArrayList<>();
//        遍历所有结果 存储
        for (Department depart : all) {
            if (depart.getParentId() == null) {   //父id等于空
                deptTree.add(depart);
            } else {   //如果不为空 就添加到顶级部门的所属儿子中，引用数据类型存储的为内存地址
                //1 获取父id
                Long parentId = depart.getParentId();
                //2 通过父id 找到顶级部门
                Department parentDept = hashMap.get(parentId);
                //3 存储
                parentDept.getChildren().add(depart);
            }
        }
        //把  depTree 添加到缓存里
       // redisTemplate.boundValueOps("deptTree").set(deptTree);
        return deptTree;


//        //1.一次性查询出所有数据，放到内存中，可以使用map
//        List<Department> all = dao.selectList(null);
//
//        //2.重组数据(部门ID-部门信息)，方便查找
//        Map<Long, Department> map = new HashMap<>();
//        for (Department department : all) {
//            map.put(department.getId(), department);
//        }
//
//        //3.创建部门树结果集（部门树结果中直接存储的都是顶级部门，其他部门都存储在父部门中）
//        List<Department> deptTree = new ArrayList<>();
//
//        //4.遍历所有的部门，开始添加树信息
//        for (Department department : all) {
//            if (department.getParentId() == null) { //如果为null，就是顶级部门。
//                //4.0 如果是顶级部门，就添加到结果集中
//                deptTree.add(department);
//            }else{   //如果不为null，就添加到父部门的所属儿子中（注意，因为是引用数据类型，所以只遍历一次即可）。
//                //4.1 获取当前部门的父部门ID
//                Long parent_id = department.getParentId();
//                //4.2 从第2步整理好的信息中获取对应的部门信息
//                Department parentDepartment = map.get(parent_id);
//                //4.3 将自己装到父部门的children中
//                parentDepartment.getChildren().add(department);
//            }
//        }
//        return deptTree;
    }
}
